﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace CantinhodaCegonha.Models.BingApi
{
    public class BingSearchClient
    {
        private string bingJsonApiUrl;
        private string bingApiKey;
        private string bingSiteQueryPiece;
        
        public BingSearchClient() : this(
            ConfigurationManager.AppSettings["BingJsonApiUrl"], 
            ConfigurationManager.AppSettings["BingApiKey"],
            ConfigurationManager.AppSettings["BingSiteQueryPiece"])
        { }

        public BingSearchClient(string bingJsonApiUrl, string bingApiKey, string bingSiteQueryPiece)
        {
            this.bingJsonApiUrl = bingJsonApiUrl;
            this.bingApiKey = bingApiKey;
            this.bingSiteQueryPiece = bingSiteQueryPiece;
        }

        public SearchResponse RunSearch(string query)
        {
            var url = string.Format("{0}?Appid={1}&sources=web&query={2} {3}",
                this.bingJsonApiUrl, this.bingApiKey, this.bingSiteQueryPiece, query);
            var result = string.Empty;
            var webRequest = WebRequest.Create(url);
            webRequest.Timeout = 2000;
            using (var response = webRequest.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var receiveStream = response.GetResponseStream();
                    if (receiveStream != null)
                    {
                        var stream = new StreamReader(receiveStream);
                        result = stream.ReadToEnd();
                    }
                }
            }
            if (string.IsNullOrEmpty(result))
                return null;
            var javaScriptSerializer = new JavaScriptSerializer();
            var apiResponse = javaScriptSerializer.Deserialize<BingApiSearchResponse>(result);
            return apiResponse.SearchResponse;
        }
    }
}